class_name DialogBox
extends Node2D
#@onready var label: RichTextLabel = $MarginContainer/label2
@onready var label: RichTextLabel = $MarginContainer/MarginContainer/Label

#每个字符显示所花的时间
@export var displayTimePerLetter :=0.07
var textTweener : Tween
var isTextDisplayFinished :=true

#当对话结束后发送
signal  textDisplayIsClosing()

func _ready() -> void:

	hide()



	
func _input(event: InputEvent) -> void:
	if event.is_action_pressed("mouse_left"):
		forceFullDisplayOrHide()
	
#展示指定文本
func displayText(text :String):
	label.visible_ratio=0.0
	label.text=text

	show()
	
	# 等待一帧让富文本排版生效，再获取内容高度
	await get_tree().process_frame
	

	#启动动画
	tweenText()
	
#动画逐字显示
func tweenText():
	isTextDisplayFinished=false
	
	#计算总的动画时间
	var nbCarac =strip_bbcode(label.text).length()
	var totalDisplayTime :float=displayTimePerLetter*nbCarac

	#安全检查
	if textTweener !=null:
		textTweener.kill()
	textTweener=get_tree().create_tween()
	textTweener.tween_property(
		label,
		"visible_ratio",
		1.0,
		totalDisplayTime
	)
	await textTweener.finished
	_text_display_finished()
	

#中断动画或关闭面板
func forceFullDisplayOrHide():
	#立即消动画并将文字全部显示
	if !isTextDisplayFinished:
		if textTweener!=null:
			textTweener.kill()
			textTweener=null
		label.visible_ratio=1.0
		_text_display_finished()
	else :
		textDisplayIsClosing.emit()
	
	
func _text_display_finished():
	isTextDisplayFinished=true
	

#去除 BBcode 标签
func strip_bbcode(source:String)->String:
	var regex = RegEx.new()
	regex.compile("\\[.+?\\]")
	return regex.sub(source,"",true)


func _on_label_minimum_size_changed() -> void:
		# 获取内容宽度
	var content_width = label.get_content_width()
	print("content_width========",content_width)
	if content_width > 270 :
		label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART  # 开启自动换行
	
